import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import '../services/api_service.dart';
import '../services/app_state_service.dart';
import '../services/storage_service.dart';
import '../widgets/common_button.dart';
import '../widgets/common_text_field.dart';
import 'base_page.dart';
import 'home_page.dart';
import 'register_page.dart';

/// 用户登录页面
/// 支持店主登录和员工登录两种模式
class LoginPage extends BasePage {
  const LoginPage({super.key});

  @override
  State<LoginPage> createState() => _LoginPageState();
}

class _LoginPageState extends BasePageState<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  
  bool _isEmployeeLogin = false;
  bool _rememberPassword = false;
  bool _autoLogin = false;

  @override
  void initState() {
    super.initState();
    // 写死测试账号密码
    _usernameController.text = '18251846048';
    _passwordController.text = '111111';
    _loadSavedCredentials();
  }

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  @override
  Widget buildPageContent(BuildContext context) {
    return SafeArea(
      child: SingleChildScrollView(
        padding: EdgeInsets.all(24.w),
        child: Form(
          key: _formKey,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(height: 60.h),
              
              // Logo和标题
              Center(
                child: Column(
                  children: [
                    Container(
                      width: 80.w,
                      height: 80.w,
                      decoration: BoxDecoration(
                        color: Theme.of(context).primaryColor,
                        borderRadius: BorderRadius.circular(20.r),
                      ),
                      child: Icon(
                        Icons.car_repair,
                        size: 40.sp,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(height: 24.h),
                    Text(
                      'QXXZS',
                      style: TextStyle(
                        fontSize: 32.sp,
                        fontWeight: FontWeight.bold,
                        color: Colors.black87,
                      ),
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      '汽车维修管理系统',
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 60.h),
              
              // 登录模式切换
              Container(
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Row(
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            _isEmployeeLogin = false;
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 12.h),
                          decoration: BoxDecoration(
                            color: !_isEmployeeLogin ? Colors.white : Colors.transparent,
                            borderRadius: BorderRadius.circular(8.r),
                            boxShadow: !_isEmployeeLogin
                                ? [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.1),
                                      blurRadius: 4,
                                      offset: const Offset(0, 2),
                                    ),
                                  ]
                                : null,
                          ),
                          child: Text(
                            '店主登录',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: !_isEmployeeLogin ? FontWeight.w600 : FontWeight.normal,
                              color: !_isEmployeeLogin ? Colors.black87 : Colors.grey[600],
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          setState(() {
                            _isEmployeeLogin = true;
                          });
                        },
                        child: Container(
                          padding: EdgeInsets.symmetric(vertical: 12.h),
                          decoration: BoxDecoration(
                            color: _isEmployeeLogin ? Colors.white : Colors.transparent,
                            borderRadius: BorderRadius.circular(8.r),
                            boxShadow: _isEmployeeLogin
                                ? [
                                    BoxShadow(
                                      color: Colors.black.withOpacity(0.1),
                                      blurRadius: 4,
                                      offset: const Offset(0, 2),
                                    ),
                                  ]
                                : null,
                          ),
                          child: Text(
                            '员工登录',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                              fontSize: 16.sp,
                              fontWeight: _isEmployeeLogin ? FontWeight.w600 : FontWeight.normal,
                              color: _isEmployeeLogin ? Colors.black87 : Colors.grey[600],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              SizedBox(height: 40.h),
              
              // 用户名输入框
              CommonTextField(
                controller: _usernameController,
                labelText: '用户名',
                hintText: '请输入用户名',
                prefixIcon: Icons.person_outline,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入用户名';
                  }
                  return null;
                },
              ),
              SizedBox(height: 20.h),
              
              // 密码输入框
              CommonTextField(
                controller: _passwordController,
                labelText: '密码',
                hintText: '请输入密码',
                prefixIcon: Icons.lock_outline,
                obscureText: true,
                validator: (value) {
                  if (value == null || value.isEmpty) {
                    return '请输入密码';
                  }
                  if (value.length < 6) {
                    return '密码长度不能少于6位';
                  }
                  return null;
                },
              ),
              SizedBox(height: 16.h),
              
              // 记住密码和自动登录
              Row(
                children: [
                  Checkbox(
                    value: _rememberPassword,
                    onChanged: (value) {
                      setState(() {
                        _rememberPassword = value ?? false;
                      });
                    },
                    activeColor: Theme.of(context).primaryColor,
                  ),
                  Text(
                    '记住密码',
                    style: TextStyle(fontSize: 14.sp),
                  ),
                  SizedBox(width: 20.w),
                  Checkbox(
                    value: _autoLogin,
                    onChanged: (value) {
                      setState(() {
                        _autoLogin = value ?? false;
                      });
                    },
                    activeColor: Theme.of(context).primaryColor,
                  ),
                  Text(
                    '自动登录',
                    style: TextStyle(fontSize: 14.sp),
                  ),
                ],
              ),
              SizedBox(height: 32.h),
              
              // 登录按钮
              CommonButton(
                text: '登录',
                onPressed: _login,
                isLoading: isLoading,
                width: double.infinity,
              ),
              SizedBox(height: 20.h),
              
              // 忘记密码和注册
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: _forgotPassword,
                    child: Text(
                      '忘记密码？',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Theme.of(context).primaryColor,
                      ),
                    ),
                  ),
                  TextButton(
                    onPressed: () {
                      navigateTo(const RegisterPage());
                    },
                    child: Text(
                      '立即注册',
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Theme.of(context).primaryColor,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 加载保存的凭据
  void _loadSavedCredentials() {
    // 这里可以从本地存储加载保存的用户名和密码
    // 简化处理，实际项目中应该从StorageService获取
  }

  /// 登录
  Future<void> _login() async {
    if (!_formKey.currentState!.validate()) {
      return;
    }

    showLoading('登录中...');

    try {
      final result = await ApiService.login(
        username: _usernameController.text.trim(),
        password: _passwordController.text,
        isEmployee: _isEmployeeLogin,
      );

      if (result.success) {
        // 登录成功，保存用户信息到状态管理
        if (result.userData != null) {
          // 获取AppStateService并保存用户信息
          final appState = Provider.of<AppStateService>(context, listen: false);
          await appState.login(
            result.userData!.id,
            result.userData!.tel,
            result.userData!.username,
            _passwordController.text,
          );
          
          showSuccess('登录成功');
          
          // 保存登录设置
          if (_rememberPassword) {
            // 保存密码到本地存储
            await StorageService.saveString('saved_password', _passwordController.text);
          }
          if (_autoLogin) {
            // 设置自动登录
            await StorageService.saveBool('auto_login', true);
          }
          
          // 跳转到首页
          replaceWith(const HomePage());
        } else {
          showError('登录失败，请重试');
        }
      } else {
        showError(result.message);
      }
    } catch (e) {
      showError('网络错误，请稍后重试');
    } finally {
      hideLoading();
    }
  }

  /// 忘记密码
  void _forgotPassword() {
    // 实现忘记密码功能
    showInfo('忘记密码功能待实现');
  }
}